<?php
namespace app\common\service;

use app\common\helper\WeixinHelper;
use app\common\util\Util;
use think\Db;
use think\Model;

class TemplateStoreService extends BaseService
{

    /**
     * 获取最新消息，包含最新班级和最新课程
     * @param $sid
     * @return mixed
     */
    public function getNewInfo($sid)
    {
        $self_academy = $this->getStoreAcademyId($sid);
        $new_class = $this->hasNewClass($sid, $self_academy);
        $new_course = $this->hasNewCourse($sid, $self_academy);
        if ($new_class['status'] == 1) {
            $data['new_class'] = true;
            $data['classid'] = $new_class['data'];
        } else {
            $data['new_class'] = false;
        }

        if ($new_course['status'] == 1) {
            $data['new_course'] = true;
            $data['courseid'] = $new_course['data'];
        } else {
            $data['new_course'] = false;
        }

//        $data['new_class'] = $this->hasNewClass($sid, $self_academy);
//        $data['new_course'] = $this->hasNewCourse($sid, $self_academy);
        return $data;
    }

    public function checkAcademy($sid)
    {
        $tpl_academy = db('store')->where(['store_id' => config('template_sid')])->value('academy_id');
        $self_academy = db('store')->where(['store_id' => $sid])->value('academy_id');
        if ($tpl_academy != $self_academy) {
            return false;
        }
    }

    /**
     * 获取店铺学院ID
     * @param $sid
     * @return mixed
     */
    public function getStoreAcademyId($sid)
    {
        return db('store')->where(['store_id' => $sid])->value('academy_id');
    }

    /**
     * 判断是否有最新班级
     * @param $sid
     * @param $self_academy_id
     * @return bool
     */
    public function hasNewClass($sid, $self_academy_id)
    {
        //查询模版店铺发布的最后班级的时间
        $tpl_last_class = db('classes')
            ->field('classid,addtime')
            ->where(['sid' => config('template_sid'), 'academy_id' => $self_academy_id])
            ->order('addtime DESC')
            ->find();
        $tpl_last_class_time = $tpl_last_class['addtime'];
        //查询最后引入的班级的时间
        $last_class_time = db('classes')->where(['sid' => $sid, 'academy_id' => $self_academy_id])->order('addtime DESC')->value('addtime');
        return $tpl_last_class_time > $last_class_time ? ['status' => 1, 'data' => $tpl_last_class['classid']] : ['status' => 0];
    }

    /**
     * 判断是否有最新课程
     * @param $sid
     * @param $self_academy_id
     * @return bool
     */
    public function hasNewCourse($sid, $self_academy_id)
    {
        $tpl_last_course = db('course')
            ->field('addtime,courseid')
            ->where([
                'sid' => config('template_sid'),
                'academy_id' => $self_academy_id,
                'release_status' => 1,
                'course_status' => 1
            ])
            ->order('addtime DESC')
            ->find();
        $last_course_time = db('course')
            ->where([
                'sid' => $sid,
                'academy_id' => $self_academy_id,
                'course_status' => ['<>', -1]
            ])
            ->order('addtime DESC')
            ->value('addtime');
        $tpl_last_course_time = $tpl_last_course['addtime'];

        return $tpl_last_course_time > $last_course_time ? ['status' => 1, 'data' => $tpl_last_course['courseid']] : ['status' => 0];
    }


    /**
     * 获取班级库列表
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getClassLibrary($sid, $search, $p, $pageSize)
    {
        $academy_id = $this->getStoreAcademyId($sid);
        $where = [
            'sid' => config('template_sid'),
            'academy_id' => $academy_id,
            'status' => ['<>', -1]
        ];
        if ($search) {
            $where['name'] = ['like', "%$search%"];
        }

        $where['status'] = 1;
        $count = db('classes')->where($where)->count();
        $list = db('classes')
            ->field('classid,name')
            ->where($where)
            ->order('classid DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();

        //判断当前店铺是否加入过此班级
        if ($list) {
            foreach ($list as $k => $v) {
                $sync_where = [
                    'sid' => $sid,
                    'status' => 1,
                    'academy_id' => $academy_id,
                    'origin_classid' => $v['classid']
                ];
                $sync_status = db('classes')->where($sync_where)->find();
                $list[$k]['sync_status'] = $sync_status ? 1 : 0;
            }
        }

        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 获取课程库列表
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     */
    public function getCourseLibrary($sid, $search, $p, $pageSize)
    {
        $academy_id = $this->getStoreAcademyId($sid);
        $where = [
            'sid' => config('template_sid'),
            'academy_id' => $academy_id,
            'release_status' => 1,
            'course_status' => ['in', [0, 1]]
        ];
        if ($search) {
            $where['name'] = ['like', "%$search%"];
        }

        $count = db('course')->where($where)->count();
        $list = db('course')
            ->field('courseid,name,addtime,edittime')
            ->where($where)
            ->order('courseid DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                //查询课程关联的班级信息
                $classes = db('course_class cc')
                    ->field('c.name')
                    ->join('classes c', 'cc.classid=c.classid')
                    ->where(['cc.courseid' => $v['courseid']])
                    ->select();
                $classes_arr = [];
                if ($classes) {
                    foreach ($classes as $key => $val) {
                        $classes_arr[$key] = $val['name'];
                    }
                    $list[$k]['classes'] = implode('、', $classes_arr);
                } else {
                    $list[$k]['classes'] = '暂无';
                }

                //判断当前店铺是否加入过此课程
                $sync_where = [
                    'sid' => $sid,
                    'academy_id' => $academy_id,
                    'origin_courseid' => $v['courseid'],
                    'course_status' => ['<>', -1]
                ];
                $sync_status = db('course')->where($sync_where)->find();
                $list[$k]['sync_status'] = $sync_status ? 1 : 0;

                //判断模版店铺是否再次编辑过内容
                $list[$k]['reedit_status'] = $v['edittime'] > $v['addtime'] ? 1 : 0;
            }
        }

        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 模版店铺发布课程
     * @param $sid
     * @param $course_id
     * @return array
     */
    public function releaseCourse($sid, $course_id)
    {
        if (!$this->isTemplateStore($sid)) {
            return ['status' => 0, 'msg' => '店铺信息有误'];
        }

        $course = db('course')->where(['sid' => $sid, 'courseid' => $course_id, 'release_status' => 0, 'course_status' => ['<>', -1]])->find();
        if (!$course) {
            return ['status' => 0, 'msg' => '此课程不存在'];
        }

        //更改发布状态
        $result = db('course')->where(['courseid' => $course_id])->setField('release_status', 1);

        //推送模版消息
        $wx_tpl_service = new WxTplMsgService();
        $sids = $this->getSameAcademyStoreIdList($course['academy_id']);
        if ($sids) {
            foreach ($sids as $k => $v) {
                $wx_tpl_service->send($v, $course_id, 'template_store_course');
            }
        }

        return $result === false ? ['status' => 0, 'msg' => '发布失败'] : ['status' => 1, 'msg' => '发布成功'];
    }


    /**
     * 获取同学院的店铺Id
     * @param $academy_id
     * @return array
     */
    public function getSameAcademyStoreIdList($academy_id)
    {
        $store_list = db('store')->field('store_id')->where(['store_id' => ['<>', config('template_sid')], 'academy_id' => $academy_id])->select();
        $sids = [];
        if ($store_list) {
            foreach ($store_list as $k => $v) {
                $sids[$k] = $v['store_id'];
            }
        }
        return $sids;
    }


    /**
     * 客户店铺引用班级
     * @param $sid
     * @param $class_id
     * @return array
     */
    public function quoteClass($sid, $class_id, $campus_id)
    {
        //判断此课程是否为模版店铺发布
        $tpl_sid = config('template_sid');
        $tpl_academy_id = db('store')->where(['store_id' => $tpl_sid])->value('academy_id');
        $tpl_class = db('classes')
            ->where([
                'classid' => $class_id,
                'sid' => $tpl_sid,
                'status' => ['<>', -1],
                'academy_id' => $tpl_academy_id
            ])
            ->find();
        if (empty($tpl_class)) {
            return ['status' => 0, 'msg' => '该班级不存在'];
        }

        //查询自身店铺是否已经引入
//        $same_class = db('classes')->where(['sid' => $sid, 'status' => ['<>', -1], 'origin_classid' => $class_id])->find();
        //再次引用
        $same_class = db('classes')->where(['sid' => $sid, 'origin_classid' => $class_id, 'campus_id' => ['in', $campus_id]])->select();
        if ($same_class) {
            $same_flag = true;
            $old_campus_ids = [];
            foreach ($same_class as $k => $v) {
                $old_campus_ids[$k] = $v['campus_id'];  //保存之前引用的校区ID

                if ($v['status'] == -1) {
                    $res = db('classes')->where(['classid' => $v['classid']])->setField('status', 1);
                    if (!$res) {
                        $same_flag = false;
                    }
                }
            }

            $campus_id_intersect = array_intersect($old_campus_ids, $campus_id); //保存交集
            $campus_id_diff = array_diff($old_campus_ids, $campus_id_intersect); //保存差集
            if ($campus_id_diff) {
                //差集为真的情况，则差集数据还需插入
                $campus_id = $campus_id_diff;
            } else {
                //不存在差集，则说明再次引用时，在之前已全部插入进来了
                return $same_flag == false ? ['status' => 0, 'msg' => '引用失败'] : ['status' => 1, 'msg' => '引用成功'];
            }

        }

        //查询自身店铺是否存在相同名称的班级
        /*$same_name_class = db('classes')->where(['sid' => $sid, 'name' => $tpl_class['name'], 'status' => ['<>', -1]])->find();
        if($same_name_class){
            return ['status' => 0, 'msg' => '已存在相同名称的班级'];
        }*/

        $academy_id = $this->getStoreAcademyId($sid);
        $data = [
            'name' => $tpl_class['name'],
            'upper_limit' => $tpl_class['upper_limit'],
            'description' => $tpl_class['description'],
            'addtime' => time(),
            'status' => 1,
            'sid' => $sid,
            'academy_id' => $academy_id,
            'origin_classid' => $tpl_class['classid']
        ];

        //查询班级关联的课程
        $tpl_relate_course = db('course_class cc')
            ->field('cr.*')
            ->join('classes c', 'c.classid=cc.classid')
            ->join('course cr', 'cc.courseid=cr.courseid')
            ->where(['c.classid' => $class_id, 'c.status' => ['<>', -1], 'cr.release_status' => 1, 'cr.course_status' => 1])
            ->select();

        foreach ($campus_id as $key => $val) {
            $data['campus_id'] = $val; //校区ID

            // 启动事务
            Db::startTrans();
            //插入班级
            $inser_class_id = db('classes')->insertGetId($data);

            if ($tpl_relate_course) {
                $insert_course_data = [];
                $courseService = new CourseService();

                foreach ($tpl_relate_course as $k => $v) {
                    //查询自身店铺是否引入相关联的课程
                    $self_relate_course = db('course')->where(['sid' => $sid, 'origin_courseid' => $v['courseid'], 'course_status' => 1])->find();
                    if (!$self_relate_course) {
                        $insert_course_data['sid'] = $sid;
                        $insert_course_data['name'] = $v['name'];
                        $insert_course_data['speaker'] = $v['speaker'];
                        $insert_course_data['schooltime'] = $v['schooltime'];
                        $insert_course_data['schoolovertime'] = $v['schoolovertime'];
                        $insert_course_data['description'] = $v['description'];
                        $insert_course_data['content'] = $v['content'];
                        $insert_course_data['pic'] = $v['pic'];
                        $insert_course_data['addtime'] = time();
                        $insert_course_data['academy_id'] = $academy_id;
                        $insert_course_data['origin_courseid'] = $v['courseid'];

                        //自动插入关联课程数据
                        $insert_course_id = db('course')->insertGetId($insert_course_data);
                        if (!$insert_course_id) {
                            Db::rollback();
                            return ['status' => 0, 'msg' => '引用课程失败'];
                        }
                        //更新课程二维码
                        $qr_code_res = $courseService->getCourseQrcodeUrl($sid, $insert_course_id);
                        if ($qr_code_res['status'] == 0) {
                            Db::rollback();
                            return ['status' => 0, 'msg' => '更新课程二维码失败'];
                        }

                        //写入课程关联班级表
                        $course_class_data = [
                            'courseid' => $insert_course_id,
                            'classid' => $inser_class_id,
                            'addtime' => time()
                        ];
                        $course_class_res = db('course_class')->insert($course_class_data);
                        if (!$course_class_res) {
                            Db::rollback();
                            return ['status' => 0, 'msg' => '写入关联数据失败'];
                        }
                    }
                }
            }

            Db::commit();
        }

        return ['status' => 1, 'msg' => '引用成功'];
    }


    /**
     * 客户店铺取消引用班级
     * @param $sid
     * @param $class_id 模版班级库的班级ID
     * @return array
     */
    public function cancelQuoteClass($sid, $class_id)
    {
        $academy_id = $this->getStoreAcademyId($sid);
        $where = [
            'sid' => $sid,
//            'classid' => $class_id,
            'origin_classid' => $class_id,
            'academy_id' => $academy_id,
//            'campus_id' => ['in', $campus_id],
            'status' => ['<>', -1]
        ];

        $class = db('classes')->where($where)->select();
        if (!$class) {
            return ['status' => 0, 'msg' => '班级不存在'];
        } else {
            $class_ids = [];
            foreach ($class as $k => $v) {
                $class_ids[$k] = $v['classid'];
            }
        }

        //软删除
//        $result = db('classes')->where(['classid' => $class['classid']])->setField('status', -1);
        $result = db('classes')->where(['classid' => ['in', $class_ids]])->setField('status', -1);
        return $result == false ? ['status' => 0, 'msg' => '取消引用失败'] : ['status' => 1, 'msg' => '取消引用成功'];
    }


    /**
     * 客户店铺引用课程
     * @param $sid
     * @param $course_id
     * @return array
     */
    public function quoteCourse($sid, $course_id)
    {
        //判断是否为模版店铺发布的课程
        $tpl_sid = config('template_sid');
        $tpl_academy_id = db('store')->where(['store_id' => $tpl_sid])->value('academy_id');
        $tpl_course = db('course')
            ->where([
                'sid' => $tpl_sid,
                'courseid' => $course_id,
                'academy_id' => $tpl_academy_id,
                'release_status' => 1,
                'course_status' => ['<>', -1]
            ])
            ->find();

        if (!$tpl_course) {
            return ['status' => 0, 'msg' => '该课程不存在'];
        }

        //查询本店铺是否已经引入
        /*$same_course = db('course')->where(['sid' => $sid, 'origin_courseid' => $course_id, 'course_status' => ['<>', -1]])->find();
        if($same_course){
            return ['status' => 0, 'msg' => '该课程已引入'];
        }*/
        //再次引用
        $same_course = db('course')->where(['sid' => $sid, 'origin_courseid' => $course_id])->find();
        if ($same_course['course_status'] == -1) {
            $res = db('course')->where(['sid' => $sid, 'origin_courseid' => $course_id])->setField('course_status', 1);
            return $res == false ? ['status' => 0, 'msg' => '引用失败'] : ['data' => $same_course['courseid'], 'status' => 1, 'msg' => '引用成功！'];
        } elseif ($same_course['course_status'] > -1) {
            return ['status' => 0, 'msg' => '该课程已引入'];
        }

        $academy_id = $this->getStoreAcademyId($sid);
        $course_data = [
            'sid' => $sid,
            'name' => $tpl_course['name'],
            'speaker' => $tpl_course['speaker'],
            'schooltime' => $tpl_course['schooltime'],
            'schoolovertime' => $tpl_course['schoolovertime'],
            'description' => $tpl_course['description'],
            'content' => $tpl_course['content'],
            'pic' => $tpl_course['pic'],
            'addtime' => time(),
            'academy_id' => $academy_id,
            'origin_courseid' => $course_id,
            'poster_imgs' => $tpl_course['poster_imgs'],
            'face_sign_code' => Util::getRandomStr(10)
        ];

        // 启动事务
        Db::startTrans();

        //插入课程数据
        $course_insert_id = db('course')->insertGetId($course_data);
        if (!$course_insert_id) {
            Db::rollback();
            return ['status' => 0, 'msg' => '引用课程失败'];
        }
        //同步课程二维码
        $courseService = new CourseService();
        $qr_code_res = $courseService->getCourseQrcodeUrl($sid, $course_insert_id);
        if ($qr_code_res['status'] == 0) {
            Db::rollback();
            return ['status' => 0, 'msg' => '引用课程失败.'];
        }

        //查询模版课程关联的班级信息
        $relate_tpl_class = db('course_class cc')
            ->field('c.classid')
            ->join('classes c', 'cc.classid=c.classid')
            ->where(['cc.courseid' => $course_id, 'c.status' => ['<>', -1]])
            ->select();
        $relate_tpl_class_ids = [];  //保存classid的一维数组
        if ($relate_tpl_class) {
            foreach ($relate_tpl_class as $k => $v) {
                $relate_tpl_class_ids[$k] = $v['classid'];
            }
            //查询自身店铺是否全部引用了班级
            $relate_self_class = db('classes')
                ->field('classid')
                ->where([
                    'sid' => $sid,
                    'academy_id' => $academy_id,
                    'origin_classid' => ['in', $relate_tpl_class_ids],
                    'status' => ['<>', -1]
                ])
                ->select();
            //全部引用才插入课程班级关联数据  其他情况则通过手动完善
            if (count($relate_tpl_class) == count($relate_self_class)) {
                $course_class_data = [];
                foreach ($relate_self_class as $key => $val) {
                    $course_class_data[$key]['courseid'] = $course_insert_id;
                    $course_class_data[$key]['classid'] = $val['classid'];
                    $course_class_data[$key]['addtime'] = time();
                }
                $course_class_result = db('course_class')->insertAll($course_class_data);
                if ($course_class_result == false) {
                    Db::rollback();
                    return ['status' => 0, 'msg' => '引用课程失败！'];
                }
            }
        }
        //提交事务
        Db::commit();
        return ['data' => $course_insert_id, 'status' => 1, 'msg' => '引用课程成功！'];
    }


    /**
     * 客户店铺取消课程引用
     * @param $sid
     * @param $course_id 模版店铺课程库课程ID
     * @return array
     */
    public function cancelQuoteCourse($sid, $course_id)
    {
        $academy_id = $this->getStoreAcademyId($sid);
        $where = [
            'sid' => $sid,
            'origin_courseid' => $course_id,
            'academy_id' => $academy_id,
            'course_status' => ['<>', -1]
        ];
        $course = db('course')->where($where)->find();
        if (!$course) {
            return ['status' => 0, 'msg' => '此课程不存在'];
        }

        //软删除
        $result = db('course')->where(['courseid' => $course['courseid']])->setField('course_status', -1);
        return $result == false ? ['status' => 0, 'msg' => '取消引用失败'] : ['status' => 1, 'msg' => '取消引用成功'];
    }


    /**
     * 微信端管理员确认引用班级
     * @param $uid
     * @param $sid
     * @param $class_id
     * @return array
     */
    public function adminQuoteClass($uid, $sid, $class_id)
    {
        //判断是否为管理员
        if (!$this->isAdmin($sid, $uid)) {
            return ['status' => 0, 'msg' => '非法请求'];
        }

        return $this->quoteClass($sid, $class_id);
    }


    /**
     * 微信端管理员确认引用课程
     * @param $uid
     * @param $sid
     * @param $course_id
     * @return array
     */
    public function adminQuoteCourse($uid, $sid, $course_id)
    {
        //判断是否为管理员
        if (!$this->isAdmin($sid, $uid)) {
            return ['status' => 0, 'msg' => '非法请求'];
        }

        return $this->quoteCourse($sid, $course_id);
    }

    /**
     * 判断是否管理员
     * @param $sid
     * @param $uid
     * @return bool
     */
    private function isAdmin($sid, $uid)
    {
        $user = db('user_integral')->where(['userid' => $uid, 'sid' => $sid])->find();
        return $user['is_administrator'] != 1 ? false : true;
    }


    /**
     * 引用模版内容库
     * @param $sid
     * @param $mid
     * @return array
     */
    public function quoteMagazine($sid, $mid)
    {
        //查询是否为模版内容
        $tpl_magazine = db('magazine')->where(['sid' => config('template_sid'), 'mid' => $mid, 'status' => 1])->find();
        if (!$tpl_magazine) {
            return ['status' => 0, 'msg' => '模版内容不存在'];
        }

        $data = [
            'sid' => $sid,
            'title' => $tpl_magazine['title'],
            'subtitle' => $tpl_magazine['subtitle'],
            'view_pic' => $tpl_magazine['view_pic'],
            'content' => $tpl_magazine['content'],
            'create_time' => time(),
            'status' => 1,
            'academy_id' => $this->getStoreAcademyId($sid),
            'origin_mid' => $mid,
        ];

        $result = db('magazine')->insert($data);

        return $result == false ? ['status' => 0, 'msg' => '引用失败'] : ['status' => 1, 'msg' => '引用成功'];
    }


    /**
     * 取消引用模版内容库
     * @param $sid
     * @param $mid 模版内容库ID
     * @return array
     */
    public function cancelQuoteMagazine($sid, $mid)
    {
        $tpl_magazine = db('magazine')->where(['sid' => config('template_sid'), 'mid' => $mid, 'status' => 1])->find();
        if (!$tpl_magazine) {
            return ['status' => 0, 'msg' => '模版内容不存在'];
        }
        $result = db('magazine')->where(['sid' => $sid, 'origin_mid' => $mid, 'status' => ['<>', -1]])->setField('status', -1);
        return $result == false ? ['status' => 0, 'msg' => '取消引用失败'] : ['status' => 1, 'msg' => '取消引用成功'];
    }


    public function addTplMsgFirst($sid, $short_id)
    {
        //判断是否为模版店铺操作
        if(!$this->isTemplateStore($sid)){
            return ['status' => 0, 'msg' => '无操作权限'];
        }
//        $short_id = 'OPENTM201605400';
        $wxService = new WeixinService();
        $result = $wxService->get_template_id($sid, $short_id);
        if ($result->errcode != 0) {
            return ['status' => 0, 'msg' => '模版消息配置失败，请重新配置或联系管理员'];
        }

        // 通过模版ID获取模版详情
        $template_id = $result->template_id;
        $tpl_info = $wxService->get_one_template($sid, $template_id);
        if (!$tpl_info) {
            return ['status' => 0, 'msg' => '模版消息配置失败，请重新配置或联系管理员。'];
        }

//        $tpl_info = [
//            "template_id" => "WrzTcDfCmh_0SI2ODZNOxjG-Gr4G0AOkDs27cqrtnU8",
//            "title" => "会员充值通知",
//            "primary_industry" => "IT科技",
//            "deputy_industry" => "互联网|电子商务",
//            "content" => "{{first.DATA}}
//课程名称：{{keyword1.DATA}}
//课程状态：{{keyword2.DATA}}
//课程进度：{{keyword3.DATA}}
//{{remark.DATA}}"
//        ];

        $data = [];
        $info = [
            'template_no' => $tpl_info['template_id'],
            'template_msg_content' => $tpl_info['content'],
            'bussiness_name' => $tpl_info['title'],
//            'template_list' => MsgService::setTemplateList($tpl_info['content']),
            'template_config_decode' => MsgService::setTemplateConfig($tpl_info['content'], 'array'),
//            'template_type' => MsgService::getNextTemplateType(),
            'template_msg' => 0,
            'template_msg_link' => ''
        ];
        $data['info'] = $info;
        $data['msg_bussiness_no'] = MsgService::getMsgBussinessNoFromConfig();
        $data['wx_keywords_type'] = MsgService::getWxKeywordsTypeFromConfig();
        $data['wx_template_msg'] = MsgService::getWxTemplateMsgFromConfig();

        $result = [
            'status' => 1,
            'msg' => '获取成功',
            'data' => $data
        ];
        return $result;
    }

    public function addTplMsgConfirm($sid, $postParam = [])
    {
        //判断是否为模版店铺操作
        if(!$this->isTemplateStore($sid)){
            return ['status' => 0, 'msg' => '无操作权限'];
        }

        $wxService = new WeixinService();
        $tpl_info = $wxService->get_one_template($sid, $postParam['template_no']);
        if(empty($tpl_info)){
            return ['status' => 0, 'msg' => '模版消息不存在'];
        }

        Db::startTrans();
        try{
            $template_list = MsgService::setTemplateList($tpl_info['content']);
            $template_config = json_encode($postParam['template_config_decode']);
//            $template_type = MsgService::getNextTemplateType();
            $template_type = $postParam['msg_bussiness_no'] + 300;

            // 通过模版短ID查询是否已初始化数据
            $init_info = db('wx_template_init')->where('template_short_no', $postParam['template_short_no'])->find();
            $save_init_data = [
                'template_msg' => $postParam['template_msg'],
                'template_msg_link' => $postParam['template_msg_link'],
                'template_msg_content' => $postParam['template_msg_content'],
                'template_list' => $template_list,
                'template_config' => $template_config,
                'status' => 1,
                'if_setting_receive' => $postParam['if_setting_receive']
            ];
            if($init_info){
                // 更新
                db('wx_template_init')->where('template_short_no', $postParam['template_short_no'])->update($save_init_data);
            } else {
                // 插入
                $save_init_data['template_short_no'] = $postParam['template_short_no'];
                $save_init_data['template_type'] = $template_type;
                db('wx_template_init')->insertGetId($save_init_data);
            }

            // 获取所有店铺ID
            $store_ids = db('store')->where('status', 1)->column('store_id');
            // 获取配置过的店铺ID
            $exist_store_ids = db('wx_template')->where(['sid' => ['in', $store_ids], 'template_type' => $template_type])->column('sid');
            // 获取未配置的店铺ID
            $diff_store_ids = array_diff($store_ids, $exist_store_ids);
            if(empty($diff_store_ids)){
                Db::rollback();
                ['status' => 0, 'msg' => '您已配置过了'];
            }

            $tpl_data = []; // 保存模版消息数据
            $set_data = []; // 保存模版消息设置数据
            foreach($diff_store_ids as $k => $v){

                if($this->isTemplateStore($v)){
                    // 模版店铺配置好了之后在此执行
                    $tpl_data[$k]['template_no'] = $postParam['template_no'];
                } else {
                    // 其他店铺新增模版
                    $short_info = $wxService->get_template_id($v, $postParam['template_short_no']);
                    $tpl_data[$k]['template_no'] = $short_info->template_id;

                }
                $tpl_data[$k]['sid'] = $v;
                $tpl_data[$k]['template_type'] = $template_type;
                $tpl_data[$k]['template_msg'] = $postParam['template_msg'];
                $tpl_data[$k]['template_msg_link'] = $postParam['template_msg_link'];
                $tpl_data[$k]['template_msg_content'] = $postParam['template_msg_content'];
                $tpl_data[$k]['template_list'] = $template_list;
                $tpl_data[$k]['template_config'] = $template_config;
                $tpl_data[$k]['status'] = 1;

                $set_data[$k]['sid'] = $v;
                $set_data[$k]['wx_template_type'] = $template_type;
                $set_data[$k]['bussiness_no'] = $postParam['msg_bussiness_no'];
                $set_data[$k]['wx_status'] = 1;
                $set_data[$k]['if_setting_receive'] = $postParam['if_setting_receive'];
            }
            // 为每个店铺插入模版消息数据
            db('wx_template')->insertAll($tpl_data);

            // 为每个店铺插入模版设置数据
            db('msg_setting')->insertAll($set_data);

            Db::commit();
            return ['status' => 1, 'msg' => '添加成功'];
        } catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '添加失败:'.$e->getMessage()];
        }

    }

    /**
     * 模版店铺删除指定模版
     * @param $sid
     * @param $template_no
     * @return \EasyWeChat\Support\Collection
     */
    public function deleteTplMsgByTemplateNo($sid, $template_no)
    {
//        $template_no = 'WrzTcDfCmh_0SI2ODZNOxjG-Gr4G0AOkDs27cqrtnU8';
        //判断是否为模版店铺操作
        if(!$this->isTemplateStore($sid)){
            return ['status' => 0, 'msg' => '无操作权限'];
        }
        $wxService = new WeixinService();
        return $wxService->delete_private_template($sid, $template_no);
    }

    public function addTplMsgToAnyStore($sid, $short_id, $link_id, $is_receive)
    {
        //判断是否为模版店铺操作
//        if(!$this->isTemplateStore($sid)){
//            return ['status' => 0, 'msg' => '无操作权限'];
//        }
        $short_id = 'TM00004';

        $store_ids = db('store')->where('status', 1)->column('store_id');
        $wxService = new WeixinService();

//        $list = $wxService->get_private_templates($sid);
        $s = '{{frist.DATA}}
订单金额：{{orderProductPrice.DATA}}
商品详情：{{orderProductName.DATA}}
收货信息：{{orderAddress.DATA}}
订单编号：{{orderName.DATA}}
{{remark.DATA}}';
        $r = MsgService::setTemplateList($s);
        $t = '{"first.DATA":{"name":"first.DATA","value":"16","custom_value":"","color":"#333333"},"keyword1.DATA":{"name":"keyword1.DATA","value":"1","custom_value":"","color":"#333333"},"keyword2.DATA":{"name":"keyword2.DATA","value":"3","custom_value":"","color":"#333333"},"keyword3.DATA":{"name":"keyword3.DATA","value":"17","custom_value":"","color":"#333333"},"keyword4.DATA":{"name":"keyword4.DATA","value":"7","custom_value":"","color":"#333333"},"remark.DATA":{"name":"remark.DATA","value":"19","custom_value":"","color":"#333333"}}';
        $r = MsgService::setTemplateConfig($t);
        dump($r);
        die();

        foreach ($store_ids as $k => $v) {
            if ($v != 1000000002) {
                // 根据模版短ID添加模版
                $result = $wxService->get_template_id($v, $short_id);
                if ($result->errcode != 0) {
                    return ['status' => 0, 'msg' => '模版消息配置失败，请重新配置或联系管理员'];
                }

                // 通过模版ID获取模版详情
                $template_id = $result->template_id;
                $tpl_info = $wxService->get_one_template($sid, $template_id);
                if (!$tpl_info) {
                    return ['status' => 0, 'msg' => '模版消息配置失败，请重新配置或联系管理员。'];
                }

                // 插入一条初始化数据，仅执行一次
                if ($k == 0) {
                    $this->initTplMsg($short_id, $link_id, $is_receive, $tpl_info['content']);
                }
                dump($tpl_info);
                die();
            }
        }
    }

    public function initTplMsg($short_id, $link_id, $is_receive, $template_msg_content)
    {
        $info = db('wx_template_init')->where('template_short_no', $short_id)->find();
        if ($info) {
            if (($info['status'] != 1) || ($info['template_msg'] != $link_id) || ($info['if_setting_receive'] != $is_receive)) {
                // 更新初始化数据
                $r = db('wx_template_init')
                    ->where('template_short_no', $short_id)
                    ->update(['status' => 1, 'template_msg' => $link_id, 'if_setting_receive' => $is_receive]);
            } else {
                return ['status' => 1, 'msg' => '初始化数据成功'];
            }
        } else {
            // 插入初始化数据
            $data = [
                'template_short_no' => $short_id,
                'template_type' => MsgService::getNextTemplateType(),
                'template_msg' => $link_id, //消息链接
                'template_msg_content' => $template_msg_content,
                'template_list' => MsgService::setTemplateList($template_msg_content),
                'template_config' => '',
                'status' => 1,
                'if_setting_receive' => $is_receive
            ];
            dump($data);
            die();

        }
    }


}







